package com.linghang.wusthelper.spider.jwc;

import com.linghang.wusthelper.dao.primary.CreditStatisticsDao;
import com.linghang.wusthelper.entity.primary.CreditStatistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * @author origin
 * 学分爬虫
 */
public class CreditStatisticSpider implements PageProcessor {

    private CreditStatisticsDao creditStatisticsDao;

    private Logger log = LoggerFactory.getLogger(getClass());

    private String stuNum;

    private String lock;

    private Site site = Site.me()
            .setRetryTimes(3)
            .setTimeOut(3000)
            .addHeader("Connection", "keep-alive")
            .addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
            .addHeader("Accept-Encoding", "gzip,deflate,sdch")
            .addHeader("Accept-Language", "zh-CN,zh;q=0.8")
            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36")
            .addHeader("Cache-Control","no-cache")
            .addHeader("Host","jwxt.wust.edu.cn")
            .setDomain("jwxt.wust.edu.cn");

    public CreditStatisticSpider(String JSESSIONID,String SERVERID,String stuNum,CreditStatisticsDao creditStatisticsDao,String lock) {
        site.addCookie("JSESSIONID",JSESSIONID);
        site.addCookie("SERVERID",SERVERID);
        this.stuNum = stuNum;
        this.creditStatisticsDao = creditStatisticsDao;
        this.lock = lock;
    }


    @Override
    public void process(Page page) {
        String creditStatisticsHtml = page.getHtml().xpath("//*[@id=\"tab1\"]/tbody").get();  // 获取学分table
        //  获取单个学分判断学分是否成功(为空则失败)
        String checkValue = page.getHtml().xpath("//*[@id=\"tab1\"]/tbody/tr[15]/td[3]/text()").get();
        if (creditStatisticsHtml != null && checkValue.length()>1){
            int result = creditStatisticsDao.check(stuNum);
            CreditStatistics creditStatistics = new CreditStatistics(stuNum,creditStatisticsHtml);
            if (result > 0){
                creditStatisticsDao.update(creditStatistics);
            }else {
                creditStatisticsDao.insert(creditStatistics);
            }
        }else {
            log.error("获取学分失败");
        }
        synchronized (lock){
            lock.notify();
        }
    }

    @Override
    public Site getSite() {
        return site;
    }
}
